<template>
  <ul class="list">
    <li
      class="item"
      v-for="letter in alphabetList"
      :key="letter"
      :ref="letter"
      @click="handleLetterclick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      {{ letter }}
    </li>
  </ul>
</template>

<script>
export default {
  name: "Alphabet",
  props: {
    alphabetList: {
      type: Array
    }
  },
  data() {
    return {
      touchStatus: false, // 是否开始触摸拖动屏幕,
      startY:0, // 字母A距离顶部的距离
      timer:null, // 节流
    };
  },
  updated() {
    // 初始化时alphabetList是一个空数组，当获取到数据，alphabetList发送变化，字母列表重新渲染
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    // 点击字母跳转到对应的城市
    handleLetterclick(e) {
      this.$bus.$emit("handleLetterclick", e.target.innerText);
    },

    // 开始滑动
    handleTouchStart(e) {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      
      if (this.touchStatus) {
        // 防止触发得太快
        if(!this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(()=>{
          const touchY = e.touches[0].clientY - 73;
          const index = Math.floor((touchY - this.startY) / 18);  // 18为每个li的高度
          if (index >= 0 && index <= this.alphabetList.length) {
            this.$bus.$emit("handleLetterclick", this.alphabetList[index]);
          }
        },16)
      }
    },

    // 结束滑动
    handleTouchEnd(e) {
      this.touchStatus = false; // 停止滑动
    }
  }
};
</script>

<style lang="less" scoped>
.list {
  position: absolute;
  top: 1.46rem;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 0.4rem;
  .item {
    text-align: center;
    padding: 0.04rem 0;
    color: skyblue;
  }
}
</style>
